package service

import (
	"fmt"
	"strings"
	"workflow/config"
	"workflow/entity"

	"gopkg.in/yaml.v2"
)

type Trigger struct {
	Type     string `yaml:"type"`
	Schedule string `yaml:"schedule"`
}

type Param struct {
	Type  string `yaml:"type"`
	Name  string `yaml:"name"`
	Value string `yaml:"value"`
}

type Node struct {
	Name         string  `yaml:"name"`
	Script       string  `yaml:"script"`
	InputParams  []Param `yaml:"inputParams"`
	OutputParams []Param `yaml:"outputParams"`
}

type DSL struct {
	Name        string  `yaml:"name"`
	Description string  `yaml:"description"`
	Trigger     Trigger `yaml:"trigger"`
	InputParams []Param `yaml:"inputParams"`
	Nodes       []Node  `yaml:"nodes"`
}

func ParseDSL(dsl string) (instance *DSL, err error) {
	instance = new(DSL)
	err = yaml.Unmarshal([]byte(dsl), instance)
	if err != nil {
		return nil, err
	}

	for index, param := range instance.InputParams {
		instance.InputParams[index] = ParseParam(param)
	}

	fmt.Println(instance)
	return instance, nil
}

func ParseParam(param Param) (returnParam Param) {
	var keyPair entity.KeyPair
	if len(param.Value) == 0 {
		return param
	}

	if strings.HasPrefix(param.Value, "$(") && strings.HasSuffix(param.Value, ")") {
		key := strings.TrimSpace(param.Value[2 : len(param.Value)-1])
		err := config.DB.Where("`key`=?", key).First(&keyPair).Error
		if err != nil {
			return param
		}
		param.Value = keyPair.Value
	}
	return param
}
